package com.qf.mybatis925.service.impl;

import com.qf.mybatis925.entity.LoginUser;
import com.qf.mybatis925.entity.TbPermission;
import com.qf.mybatis925.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailServiceImpl implements UserDetailsService{
    @Autowired
    private UserMapper UserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = UserMapper.loginByUsername(username);
        if (loginUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        String password = loginUser.getPassword();
        Set<TbPermission> permissionSet = UserMapper.selectAuthsById(loginUser.getId()); ;
        System.out.println("authsSet = " + permissionSet);

        // 需要转换为 GrantedAuthority 类型
        HashSet<GrantedAuthority> auths = new HashSet<>();
        permissionSet.forEach(permission->{
            auths.add(new SimpleGrantedAuthority(permission.getPermTag()));
        });

        User userDetails = new User(loginUser.getUsername(), loginUser.getPassword(), auths);
        return userDetails;
    }
}
